﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading.Tasks;

namespace Point2PointClient
{
    class Program
    {
        static void Main(string[] args)
        {
            byte[] data = new byte[1024];
            string input, stringData;

            IPEndPoint ipep = new IPEndPoint(IPAddress.Parse("127.0.0.1"), 9050);
            Socket udpClient = new Socket(AddressFamily.InterNetwork,
                SocketType.Dgram,
                ProtocolType.Udp);
            string welcome = "Hello,are you there?";
            data = Encoding.ASCII.GetBytes(welcome);
            udpClient.SendTo(data, data.Length, SocketFlags.None, ipep);

            IPEndPoint sender = new IPEndPoint(IPAddress.Any, 0);
            EndPoint remote = (EndPoint)sender;
            data = new byte[1024];
            int recv = udpClient.ReceiveFrom(data, ref remote);

            Console.WriteLine("Message received from{0}:", remote.ToString());
            Console.WriteLine(Encoding.ASCII.GetString(data, 0, recv));
            string remoteStr = Encoding.ASCII.GetString(data, 0, recv);
            string[] arr = remoteStr.Split(':');
            sender = new IPEndPoint(IPAddress.Parse(arr[0]), Convert.ToInt32(arr[1]));
            remote = (EndPoint)sender;
            string str = Console.ReadLine();
            while (true) {
                if (str == "one")
                {
                    Console.WriteLine("Wait input ...");
                    input = Console.ReadLine();
                    if (input == "text") { break; }
                    udpClient.SendTo(Encoding.ASCII.GetBytes(input), remote);
                    recv = udpClient.ReceiveFrom(data, ref remote);
                    stringData = Encoding.ASCII.GetString(data, 0, recv);
                    Console.WriteLine(stringData);
                }
                else {
                    recv = udpClient.ReceiveFrom(data, ref remote);
                    stringData = Encoding.ASCII.GetString(data, 0, recv);
                    Console.WriteLine(stringData);
                    Console.WriteLine("Wait input ...");
                    input = Console.ReadLine();
                    if (input == "text") { break; }
                    udpClient.SendTo(Encoding.ASCII.GetBytes(input), remote);
                }
            }
            Console.WriteLine("Stopping client");
            udpClient.Close();
        }
    }
}
